dfs and similar divide and conquer implementation *1200

Please click on ads to support us..

Python Code:

testcases = int(input())

def depth_function(input_list, depth_list, current_depth, index_left, index_right):

    if index_left == index_right:
        return None

    max_sublist = max(input_list[index_left:index_right])
    max_index = input_list.index(max_sublist)

    depth_list[max_index] = current_depth

    depth_function(input_list, depth_list, current_depth+1, index_left, max_index)
    depth_function(input_list, depth_list, current_depth+1, max_index+1, index_right)

for i in range(testcases):
    n = int(input())
    input_2 = input().split()
    permutation = list(map(int, input_2))

    depths = [0]*n

    depth_function(permutation, depths, 0, 0, n)

    print(' '.join(map(str, depths)))

C++ Code:

#include <bits/stdc++.h>
using namespace std;

typedef long long int ll;
typedef pair<ll, ll> pl;

#define N 110

ll n, a[N], dep[N];

void dfs(ll l, ll r, ll d) {
    if(l > r) return;
    ll ind = -1, mx = -1;
    for(ll i = l; i <= r; i++) if(a[i] > mx) ind = i, mx = a[i];
    dep[ind] = d;
    dfs(l, ind - 1, d + 1);
    dfs(ind + 1, r, d + 1);
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    int t; cin >> t;
    while(t--) {
        cin >> n;
        for(ll i = 0; i < n; i++) cin >> a[i];
        dfs(0, n - 1, 0);
        for(ll i = 0; i < n; i++) cout << dep[i] << " \n"[i == n - 1];
    }
}


Comments

Submit
0 Comments
More Questions

1650C - Weight of the System of Nested Segments
1097A - Gennady and a Card Game
248A - Cupboards
1641A - Great Sequence
1537A - Arithmetic Array
1370A - Maximum GCD
149A - Business trip
34A - Reconnaissance 2
59A - Word
462B - Appleman and Card Game
1560C - Infinity Table
1605C - Dominant Character
1399A - Remove Smallest
208A - Dubstep
1581A - CQXYM Count Permutations
337A - Puzzles
495A - Digital Counter
796A - Buying A House
67A - Partial Teacher
116A - Tram
1472B - Fair Division
1281C - Cut and Paste
141A - Amusing Joke
112A - Petya and Strings
677A - Vanya and Fence
1621A - Stable Arrangement of Rooks
472A - Design Tutorial Learn from Math
1368A - C+=
450A - Jzzhu and Children
546A - Soldier and Bananas